package com.shen.thread.syn;

public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket ticket = new BuyTicket();
        new Thread(ticket, "张三").start();
        new Thread(ticket, "李四").start();
        new Thread(ticket, "王五").start();

    }
}

class BuyTicket implements Runnable {
    private int ticketNum = 200;
    boolean flag = true;//外部停止

    @Override
    public void run() {
        //买票
        while (flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //同步 synchronized
    private synchronized void buy() throws InterruptedException {
        if (ticketNum <= 0) {
            flag = false;
            return;
        }
        Thread.sleep(30);

        System.out.println(Thread.currentThread().getName() + "拿到" + ticketNum--);
    }
}